import { ApiObject } from 'amis-core/lib/types'
import rsqlUtils from '@/core/utils/rsql/rsqlUtils'
import coreConstants from '@/core/constants/coreConstants'
import { RsqlDataOperator } from '@/core/utils/rsql/types/RsqlDataOperator'
import { RsqlDataOperatorEnum } from '@/core/utils/rsql/types/RsqlOperatorEnum'
import serverApiUtils from '@/core/utils/serverApiUtils'
import { SelectControlSchema } from 'amis/lib/renderers/Form/Select'
import oauth2AdminApiConfig from '@/core/oauth2/generated/apiconfig/oauth2AdminApiConfig'

class IdOfClientSelectUtils {
	getSchema = (parmas?: SelectControlSchema): SelectControlSchema => {
		const name = parmas?.name ? parmas.name : 'idOfClient'
		const mergeSchema = Object.assign(
			{
				name: name,
				type: 'select',
				label: '客户端',
				source: {
					url: serverApiUtils.getUriOrMockUri(oauth2AdminApiConfig.oauth2RegisteredClient.get),
					method: oauth2AdminApiConfig.oauth2RegisteredClient.search.method,
					data: {
						id: `\${${name}}`,
					},
					responseData: {
						[name]: `\${${name}}`,
					},
					sendOn: 'this.id !== "" && this.id !== undefined && this.id !== null',
				} as ApiObject,
				autoComplete: {
					url: serverApiUtils.getUriOrMockUri(oauth2AdminApiConfig.oauth2RegisteredClient.search),
					method: oauth2AdminApiConfig.oauth2RegisteredClient.search.method,
					responseData: {
						options: '${items|pick:label~clientName,value~id}',
					},
					requestAdaptor: (api: ApiObject, context: any): ApiObject | Promise<ApiObject> => {
						const operators: RsqlDataOperator[] = [
							{
								operator: RsqlDataOperatorEnum.LIKE_RIGHT,
								propertyName: 'clientName',
							} as RsqlDataOperator,
							{
								operator: RsqlDataOperatorEnum.EQUAL,
								propertyName: 'deleteFlag',
							} as RsqlDataOperator,
						]
						const term = context['term']
						if (term) {
							context['clientName'] = term
						}

						context['deleteFlag'] = coreConstants.notDeleteFlag
						api = rsqlUtils.addRsqlFilter(api, context, coreConstants.api.queryFilterName, operators)
						return api
					},
				} as ApiObject,
			},
			parmas,
		)

		const schema = mergeSchema
		return schema
	}
}

export default new IdOfClientSelectUtils()
